//基础Modbus数据模型
package modbus

import "errors"

type DirectionType uint8

const (
	Send    DirectionType = 0
	Receive DirectionType = 1
)

type CommandType uint8

const (
	ReadCoilStatus          CommandType = 1 //00001
	ReadInputStatus         CommandType = 2 //10001
	ReadHoldingRegisters    CommandType = 3 //40001
	ReadInputRegisters      CommandType = 4 //30001
	ForceSingleCoil         CommandType = 5
	PresetSingleRegister    CommandType = 6
	ForceMultipleCoils      CommandType = 15
	PresetMultipleRegisters CommandType = 16
)

type ModbusTCPHeader struct {
	TxNo         uint16 `json:"txNo"`
	RxNo         uint16 `json:"rxNo"`
	ProtocolType uint16 `json:"ProtocolType"` //ModbusTCP固定为0000
	Length       uint16 `json:"length"`
}

func (_this *ModbusTCPHeader) ToArray() []byte {
	buffer := make([]byte, 6)
	//buffer[0] = _this.TxNo
	//buffer[1] = _this.RxNo
	buffer[0] = byte(_this.TxNo >> 8)
	buffer[1] = byte(_this.TxNo & 0xFF)
	buffer[2] = byte(_this.ProtocolType >> 8)
	buffer[3] = byte(_this.ProtocolType & 0xFF)
	buffer[4] = byte(_this.Length >> 8)
	buffer[5] = byte(_this.Length & 0xFF)
	return buffer //fmt.Sprintf("%2X-%2X-%4X-%4X", _this.TxNo, _this.RxNo, _this.ProtocolType, _this.Length)
}

func (_this *ModbusTCPHeader) FromArray(buffer []byte) error {
	if buffer == nil || len(buffer) != 6 {
		return errors.New("buffer length error")
	}
	_this.TxNo = uint16(buffer[0])<<8 + uint16(buffer[1])
	_this.RxNo = 0 //uint16(buffer[1])
	_this.ProtocolType = uint16(buffer[2])<<8 + uint16(buffer[3])
	_this.Length = uint16(buffer[4])<<8 + uint16(buffer[5])
	return nil //fmt.Sprintf("%2X-%2X-%4X-%4X", _this.TxNo, _this.RxNo, _this.ProtocolType, _this.Length)
}

/*func (_this *ModbusTCPHeader) ToString() string {
	return ByteArrayToString(_this.ToArray())
	//return fmt.Sprintf("%2X-%2X-%4X-%4X", _this.TxNo, _this.RxNo, _this.ProtocolType, _this.Length)
}
*/
// App struct
type ModbusModel struct {
	//Direction    DirectionType `json:"direction"`    //: "send",Y
	Command   CommandType `json:"command"`   //: "01",Y
	Addr      byte        `json:"addr"`      //: "03",Y
	RegNo     uint16      `json:"regNo"`     //: "00 00",
	RegLength uint8       `json:"regLength"` //: "00 0a",
	BufferLen uint8       `json:"bufferLen"` //: "0a",
	Body      []uint16    `json:"body"`      //: "",
	//HasRegNo     bool          `json:"hasRegNo"`     //: true,Y
	//HasRegLen    bool          `json:"hasRegLen"`    //: true,Y
	//HasBufferLen bool          `json:"hasBufferLen"` //: true,Y
	//HasBody      bool          `json:"hasBody"`      //: true,Y
}

/*func (_this *ModbusModel) ToString() string {
	return ByteArrayToString(_this.ToArray())
	//return fmt.Sprintf("%s-%d-%2X-%d-%d-%d-%d-%d", _this.Direction, _this.Header, _this.Command, _this.Addr, _this.RegNo, _this.Length, _this.Addr, _this.Crc)
}

func ByteArrayToString(buffer []byte) string {
	return ""
}*/
